package com.alperez.recolourbitmap;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alperez.recolourbitmap.data.ColourKeeper;
import com.alperez.recolourbitmap.dsp.ColourProcessor;
import com.example.recolourbitmap.R;

public class MainActivity extends ActionBarActivity {

	private ImageView vImageOriginal;
	private ImageView vImageResult;
	private View vColourOriginal;
	private View vColourResult;


	private ColourProcessor mProcessor;
	
	private ColourKeeper mNewColour;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		vImageOriginal = (ImageView) findViewById(R.id.image_original);
		vImageResult = (ImageView) findViewById(R.id.image_result);
		vColourOriginal = findViewById(R.id.show_colour_old);
		vColourResult = findViewById(R.id.show_colour_new);
		vColourResult.setOnClickListener(mSelectColourListener);
		findViewById(R.id.colour_new_arrow).setOnClickListener(mSelectColourListener);

		mProcessor = new ColourProcessor(BitmapFactory.decodeResource(getResources(), R.drawable.ic_languages), 86, 0x00FFFFFF);
		vImageOriginal.setImageBitmap(mProcessor.getSourceBitmap());
		
		
		vColourOriginal.setBackgroundColor(mProcessor.getRenderedColour(mProcessor.getDarkestPixel()));
		
		
		
	}
	
	
	ProgressDialog mProgressDialog;
	private void launchPictureProcessingWithNewColour() {
		new AsyncTask<Void, Void, Long>() {

			@Override
			protected void onPreExecute() {
				mProgressDialog = new ProgressDialog(MainActivity.this);
				mProgressDialog.setIndeterminate(true);
				mProgressDialog.setMessage(MainActivity.this.getString(R.string.message_wait));
				mProgressDialog.show();
			};
			
			@Override
			protected Long doInBackground(Void... params) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				long start = System.currentTimeMillis();
				mProcessor.applyNewColour(mNewColour.getColour());
				return System.currentTimeMillis() - start;
			}
			
			@Override
			protected void onPostExecute(Long result) {
				vImageResult.setImageBitmap(mProcessor.getResultBitmap());
				mProgressDialog.dismiss();
				mProgressDialog = null;
			};
		}.execute();
	}
	
	private OnClickListener mSelectColourListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if (!flDialogOn && (mProgressDialog == null)) {
				showPeekColourDialog();
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	
	
	/*****************************  Section which implements dialog to choose new colour  ******************************************/
	private boolean flDialogOn;
	private void showPeekColourDialog() {
		if (flDialogOn) {
			throw new IllegalStateException("Method to show select colour dialog can not be called until flDialogOn is TRUE");
		}
		flDialogOn = true;
		if (mNewColour != null) {
			getColourEditField().setText(mNewColour.getColourString().substring(1));
		}
		getSelectColourDialog().show();
	}
	
	
	private AlertDialog dlgSelectColour;
	private EditText vEdtColour;
	
	private AlertDialog getSelectColourDialog() {
		if (dlgSelectColour == null) {
			View content = LayoutInflater.from(this).inflate(R.layout.select_colour_view, null);
			vEdtColour = ((EditText) content.findViewById(R.id.edt_colour));
			vEdtColour.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					//Do nothing here
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					//Do nothing here
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					if (dlgSelectColour != null) {
						dlgSelectColour.getButton(DialogInterface.BUTTON_POSITIVE)
							.setEnabled(ColourKeeper.isValidStringRepresentation(ColourKeeper.COLOR_STRING_PREFIX + s.toString()));
					}
				}
			});
			
			
			dlgSelectColour = new AlertDialog.Builder(this).setTitle(R.string.title_select_new_clor).setView(content)
				.setNegativeButton(android.R.string.cancel, null)
				.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					MainActivity.this.getWindow().getDecorView().postDelayed(new Runnable() {
						
						@Override
						public void run() {
							String val = ColourKeeper.COLOR_STRING_PREFIX + getColourEditField().getText().toString();
							if (ColourKeeper.isValidStringRepresentation(val)) {
								mNewColour = new ColourKeeper(val);
								vColourResult.setBackgroundColor(mNewColour.getColour());
								launchPictureProcessingWithNewColour();
							} else {
								Toast.makeText(MainActivity.this, R.string.err_bad_colour_format, Toast.LENGTH_SHORT).show();
							}
							flDialogOn = false;
						}
					}, 250);
					
				}
			}).create();
		}
		return dlgSelectColour;
	}
	
	private EditText getColourEditField() {
		getSelectColourDialog();
		return vEdtColour;
	}
	

}
